package edu.auctionmart

class FeedbackController {

	def authenticateService
    def scaffold = true
	
    def index() { 
		redirect(action: list)
	}
		
	def create = {	
		def view = "create"
		def principal = authenticateService.principal()
		String name = principal.getUsername()
		def userInstance = User.findByUsername(name)
		
		def auction = Auction.findById(params.id)

		Feedback fb = new Feedback()
		fb.leftBy = userInstance
		
		if (auction.seller == userInstance)
			fb.leftFor = auction.winner
		else
			fb.leftFor = auction.seller	
			
		fb.auction = auction	
		render (view: view, model: [feedbackInstance: fb])
	}
	
	def save = {
		
		def principal = authenticateService.principal()
		String name = principal.getUsername()
		def userInstance = User.findByUsername(name)
		
		if (params) {
		
			def feedbackInstance = new Feedback()
			
			def auctionTitle = params.auction.id
			def leftForName = params.leftFor.id
			def leftByName = params.leftBy.id
			
			def auction = Auction.findByAuctionTitle(auctionTitle)
			def leftFor = User.findByUsername(leftForName)
			def leftBy = User.findByUsername(leftByName)
			
			feedbackInstance.auction = auction
			feedbackInstance.leftFor = leftFor
			feedbackInstance.leftBy = leftBy
			feedbackInstance.availability = Integer.parseInt(params.availability)
			feedbackInstance.accuracy = Integer.parseInt(params.accuracy)
			feedbackInstance.communication = Integer.parseInt(params.communication)
			feedbackInstance.overallRating = Integer.parseInt(params.overallRating)
			feedbackInstance.comment = params.comment
			
			leftBy.profile.addToFeedbackGiven(feedbackInstance)
			leftFor.profile.addToFeedbackReceived(feedbackInstance)
			
			feedbackInstance.save(flush: true)
			
			flash.message = "Successfully left Feedback for ${leftFor.username}"
			redirect(controller: 'user', action:'myAccount', model: [userInstance: userInstance])	
		}
	}
		
}
